<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="130px"
    >
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基本信息" name="first">
          <el-row>
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :action="url"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeUpload"
                :headers="headers"
              >
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId">
                <el-tree-select
                  v-model="formData.deptId"
                  :data="deptList"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  placeholder="请选择归属部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工性别" prop="sex">
                <el-select v-model="formData.sex" placeholder="请选择">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="姓名" prop="nickname">
                <el-input v-model="formData.nickname" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="常驻地址" prop="address">
                <el-input v-model="formData.address" placeholder="请输入常驻地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="紧急联系人号码" prop="emergencyPhone">
                <el-input v-model="formData.emergencyPhone" placeholder="请输入紧急联系人号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否一线人员" prop="grassroots">
                <el-radio-group v-model="formData.grassroots" class="ml-4" @change="changeGrassroots">
                  <el-radio :label="true" size="large">是</el-radio>
                  <el-radio :label="false" size="large">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="账号信息" name="second">
          <el-row>
            <el-col :span="12">
              <el-form-item label="登录手机号" prop="mobile">
                <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password" v-if="!formData.id">
                <el-input
                  v-model="formData.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="密码" prop="newPassword" v-if="formData.id">
                <el-input v-model="formData.newPassword" placeholder="**********" show-password />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="收款信息" name="third">
          <el-row>
            <el-col>
              <el-form-item label="收款银行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="银行卡号" prop="bankCard">
                <el-input v-model="formData.bankCard" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="收款姓名" prop="payee">
                <el-input v-model="formData.payee" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="合规信息" name="fourth" v-if="formData.grassroots">
          <el-row>
            <el-col>
              <el-form-item label="营业执照" prop="businessLicenseUrl">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleBusinessLicenseSuccess"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="formData.businessLicenseUrl"
                    :src="formData.businessLicenseUrl"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="商家名" prop="storeOwnName">
                <el-input v-model="formData.storeOwnName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="健康证" prop="healthCertificateUrl">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleHealthCertificateSuccess"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="formData.healthCertificateUrl"
                    :src="formData.healthCertificateUrl"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="技能证书" prop="skillsCertificateUrl">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleSkillsCertificateSuccess"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="formData.skillsCertificateUrl"
                    :src="formData.skillsCertificateUrl"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="实名信息" name="five">
          <el-row>
            <el-col :span="12">
              <el-form-item label="身份证正面" prop="idCardFrontUrl" :headers="headers">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleIdCardFrontSuccess"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="formData.idCardFrontUrl"
                    :src="formData.idCardFrontUrl"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证反面" prop="idCardOppositeUrl" :headers="headers">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleIdCardOppositeSuccess"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="formData.idCardOppositeUrl"
                    :src="formData.idCardOppositeUrl"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="姓名" prop="realName">
                <el-input v-model="formData.realName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="formData.idCard" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="手机号" prop="realPhone">
                <el-input v-model="formData.realPhone" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

import { getAccessToken, getTenantId } from '@/utils/auth'
import type { TabsPaneContext } from 'element-plus'
defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  avatar: '',
  grassroots: true,
  businessLicenseUrl: '',
  healthCertificateUrl: '',
  skillsCertificateUrl: '',
  storeOwnName: '',
  idCardFrontUrl: '',
  idCardOppositeUrl: '',
  realName: '',
  realPhone: '',
  idCard: ''
})
const headers = ref({
  Authorization: 'Bearer ' + getAccessToken()
})

const url = import.meta.env.VITE_UPLOAD_URL
console.log()
const formRules = reactive<FormRules>({
  avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '常驻地址不能为空', trigger: 'blur' }],
  emergencyContact: [{ required: true, message: '紧急联系人不能为空', trigger: 'blur' }],
  emergencyPhone: [{ required: true, message: '紧急联系电话不能为空', trigger: 'blur' }],
  grassroots: [{ required: true, message: '是否一线人员不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  bankName: [{ required: true, message: '银行名称不能为空', trigger: 'blur' }],
  bankCard: [{ required: true, message: '银行卡号不能为空', trigger: 'blur' }],
  payee: [{ required: true, message: '收款人姓名不能为空', trigger: 'blur' }],
  // businessLicenseUrl: [{ required: true, message: '营业执照不能为空', trigger: 'blur' }],
  // healthCertificateUrl: [{ required: true, message: '健康证不能为空', trigger: 'blur' }],
  // storeOwnName: [{ required: true, message: '商家名不能为空', trigger: 'blur' }],
  idCardFrontUrl: [{ required: true, message: '身份证正面不能为空', trigger: 'blur' }],
  idCardOppositeUrl: [{ required: true, message: '身份证反面不能为空', trigger: 'blur' }],
  realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  realPhone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  idCard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    },
    { required: true, message: '手机号不能为空', trigger: 'blur' }
  ]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表
const imageUrl = ref('')
/** 打开弹窗 */
const open = async (type: string, code?: String) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (code) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getEditByCode(code)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      await UserApi.createUserDetail(data)
      message.success(t('common.createSuccess'))
    } else {
      data.password = undefined
      await UserApi.updateUserDetail(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: [],
    avatar: '',
    grassroots: true,
    businessLicenseUrl: '',
    healthCertificateUrl: '',
    skillsCertificateUrl: '',
    idCardFrontUrl: '',
    idCardOppositeUrl: '',
    realName: '',
    realPhone: '',
    idCard: ''
  }
  formRef.value?.resetFields()
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.avatar = response.data
}
const handleBusinessLicenseSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.businessLicenseUrl = response.data
}
const handleHealthCertificateSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.healthCertificateUrl = response.data
}
const handleSkillsCertificateSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.skillsCertificateUrl = response.data
}
const handleIdCardFrontSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.idCardFrontUrl = response.data
}
const handleIdCardOppositeSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formData.value.idCardOppositeUrl = response.data
}
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' ) {
    ElMessage.error('Avatar picture must be JPG PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传照片不能超过5MB!')
    return false
  }
  return true
}
const changeGrassroots = async(value)=>{
  if(!value){
    formData.value.businessLicenseUrl = ''
    formData.value.healthCertificateUrl = ''
    formData.value.skillsCertificateUrl = ''
    formData.value.storeOwnName = ''
  }
  console.info(value)
}
const activeName = ref('first')
</script>

<style>
.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}
</style>
<style scoped>
img {
  width: 150px;
}
</style>
